#!/bin/bash
# version 1.1 - added remount of flash drive to eliminate access time update 
#               when reading .conf files
# version 1.2 - now handles restart of unMENU on user-signal
#UNMENU_RELEASE $Revision$ $Date$
progname=$0
d=`dirname "${progname}"`
# change directory to where the unmenu.awk program resides.
cd $d
# first test that the unmenu script exists
if [ ! -f ./unmenu.awk ]
then
   echo "Sorry, $d/unmenu.awk does not seem to exist"
   exit 2
fi
# close the open file descriptors to the console
exec 0>&-
exec 1>&-
exec 2>&-
# disable access time update on flash drive.
# This will keep config file read from writing to flash drive to modify access times.
mount -o remount,noatime,nodiratime /boot
( 
    loop_count=0
    # create a lock file
    while true
    do 
        echo "Starting unmenu web-server" | logger -tunmenu-status
        awk -W re-interval -f ./unmenu.awk 2>&1 0</dev/null
        ret=$?
        echo "Exiting unmenu web-server, exit status code = $ret" | logger -tunmenu-status 
        let loop_count=$loop_count+1
        if [ $loop_count -gt 2 ]
        then
           if [ $ret = 2 ]
           then
             echo "Fatal error:Exiting uu, unmenu may already be running, exit status=$ret" | logger -tunmenu-error 
           else
             echo "Fatal error:Exiting uu, unmenu exit status code = $ret" | logger -tunmenu-error 
           fi
           break
        fi

        case $ret in
        0) echo "unmenu.awk stopped"; break ;;      # normal exit
        2) echo "unmenu.awk unable to open port.  It  may already be running";;       # locked file
        3|138) loop_count=0; continue ;;   # re-start unmenu to re-read conf files and plug-ins
        143) break ;;    # process killed
        141) loop_count=0; continue ;; # i/o error when browser closes port
        *) echo "exit status $ret - unmenu.awk will be re-started" ; loop_count=0; continue ;;
        esac
        sleep 10
        
    done 2>&1 </dev/null 
) | logger -tunmenu -plocal7.info -is &
disown %%
